package com.android.RssReader.Utils;

import info.monitorenter.cpdetector.io.CodepageDetectorProxy;
import info.monitorenter.cpdetector.io.JChardetFacade;

import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.util.Log;

import com.android.RssReader.RssReaderApplication;
import com.android.RssReader.Model.NewsInfoBean;


public class XmlParserUtil {
	public static List<NewsInfoBean> PullParseXML(String xmlPath, List<NewsInfoBean> listNews) throws Exception{
		List<NewsInfoBean> listNewsTitle;
		if(listNews == null) {
			listNewsTitle =  new ArrayList<NewsInfoBean>();
		} else {
			listNewsTitle = listNews;
		}
		NewsInfoBean NewsInfoBean = null;
		URL url = new URL(xmlPath);
		//防止遇到某些编码(如GBK)时出现错误
		//得到探测器代理对象 
		CodepageDetectorProxy detector =   CodepageDetectorProxy.getInstance(); 
		//向代理对象添加探测器 
		detector.add(JChardetFacade.getInstance());   
		//得到编码字符集对象 
		Charset charset =  detector.detectCodepage(url); 
		//得到编码名称 
		String encodingName = charset.name(); 
		Log.e("RssReader_Encoding", encodingName);
		
		XmlPullParserFactory pullParserFactory = XmlPullParserFactory.newInstance();
		XmlPullParser xmlPullParser = pullParserFactory.newPullParser();
		Log.e("PullParseXML", "getXML......");
		
		HttpGet httpRequest = new HttpGet(xmlPath);   
		HttpParams httpParameters = new BasicHttpParams(); 
		  // 请求超时
		  int timeoutConnection = 10000; 
		 HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); 
		  // Set the default socket timeout (SO_TIMEOUT)  
		 // 接收返回数据超时
		 int timeoutSocket = 30000; 
		 HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); 
		HttpResponse httpResponse = new DefaultHttpClient(httpParameters).execute(httpRequest);
		RssReaderApplication.LogD(XmlParserUtil.class,"getStatusCode():" + httpResponse.getStatusLine().getStatusCode());
		if(httpResponse.getStatusLine().getStatusCode() != 200){
			return null;
		}
		HttpEntity httpEntity = httpResponse.getEntity();
		//指定编码生成字符流
//		if(encodingName.equals("GBK") || encodingName.equals("gb2312")){
//			xmlPullParser.setInput(httpEntity.getContent(), encodingName);
//		}
//		else{
//			 xmlPullParser.setInput(httpEntity.getContent(), null);
//		}
		xmlPullParser.setInput(httpEntity.getContent(), encodingName);
		Log.e("PullParseXML", "PullParseXML....start....");
		int eventType=xmlPullParser.getEventType();
		while(eventType != XmlPullParser.END_DOCUMENT){
			String nodeName=xmlPullParser.getName();
			switch (eventType) {
			case XmlPullParser.START_DOCUMENT:
				break;
			case XmlPullParser.START_TAG:
				if("item".equals(nodeName)){
					NewsInfoBean = new NewsInfoBean();
				} 
				if("title".equals(nodeName) && NewsInfoBean != null){
					NewsInfoBean.setTitle(xmlPullParser.nextText());
				} 
				if("link".equals(nodeName)  && NewsInfoBean != null){
					NewsInfoBean.setLink(xmlPullParser.nextText());
				}
				if("description".equals(nodeName)  && NewsInfoBean != null){
					NewsInfoBean.setDescription(splitAndFilterString(xmlPullParser.nextText(), 0));
				}
				if("source".equals(nodeName)  && NewsInfoBean != null){
					NewsInfoBean.setSource(xmlPullParser.nextText());
				}
				if("author".equals(nodeName)  && NewsInfoBean != null){
					NewsInfoBean.setAuthor(xmlPullParser.nextText());
				}
				if("pubDate".equals(nodeName)  && NewsInfoBean != null){
					NewsInfoBean.setPubDate(xmlPullParser.nextText());
				}
				break;
			case XmlPullParser.END_TAG:
				if("item".equals(nodeName)){
					listNewsTitle.add(NewsInfoBean);
				}
				break;

			default:
				break;
			}
			eventType = xmlPullParser.next();
		}
		return listNewsTitle;
	}
	
	/**
	 * 删除input字符串中的html格式
	 * 
	 * @param input
	 * @param length
	 * @return
	 */
	public static String splitAndFilterString(String input, int length) {
		if (input == null || input.trim().equals("")) {
			return "";
		}
		// 去掉所有html元素,
		String str = input.replaceAll("\\&[a-zA-Z]{1,10};", "").replaceAll(
				"<[^>]*>", "");
		str = str.replaceAll("[(/>)<]", "");
//		int len = str.length();
//		if (len <= length) {
//			return str;
//		} else {
//			str = str.substring(0, length);
//			str += "......";
//		}
		return str;
	}
}
